package com.example.sunray.bluetooth.SSP;

import android.util.Log;

public final class CodecUtil {


    static CRC16 crc16 = new CRC16();

    private CodecUtil() {
    }

    public static byte[] short2bytes(short s) {
        byte[] bytes = new byte[2];
        for (int i = 1; i >= 0; i--) {
            bytes[i] = (byte) (s % 256);
            s >>= 8;
        }
        return bytes;
    }

    public static short bytes2short(byte[] bytes) {
        short s = (short) (bytes[1] & 0xFF);
        s |= (bytes[0] << 8) & 0xFF00;
        return s;
    }

    /*
     * 获取crc校验的byte形式
     */
    public static byte[] crc16Bytes(byte[] data) {
        return short2bytes(crc16Short(data));
    }

    /*
     * 获取crc校验的short形式
     */
    public static short crc16Short(byte[] data) {
        return crc16.getCrc(data);
    }
    public static char Crc16Calc(byte[] data_arr, int data_len)
    {
        char crc16 = 0;
        int i;
        for(i =0; i < (data_len); i++)
        {
            crc16 = (char)(( crc16 >> 8) | (crc16 << 8));
            crc16 ^= data_arr[i]& 0xFF;
            crc16 ^= (char)(( crc16 & 0xFF) >> 4);
            crc16 ^= (char)(( crc16 << 8) << 4);
            crc16 ^= (char)((( crc16 & 0xFF) << 4) << 1);
        }
        return crc16;
    }
    public static void test() {
        byte[] test = new byte[]{(byte)0xAA, 0x01, 0x00, 0x00, 0x00,0x00,0x00,0x04,0x00,0x00,0x04,(byte)0xD2};
        int crc1 = CRC16.calcCrc16(test);
    }
}
